import api from "./index";
import { DataSourceType, DataSourceStatus } from "@/constants/dataSource";
import type {
  DataSource,
  DataSourceQuery,
  DataSourceResponse,
  TableListResponse,
  ColumnInfo,
  TableDataQuery,
  TableDataResponse,
} from "@/types/dataSource";

// 增加延迟初始化机制
let _mockDataSources: DataSource[] | null = null;

// 获取模拟数据的函数
const getMockDataSources = (): DataSource[] => {
  if (_mockDataSources === null) {
    _mockDataSources = [
      {
        id: 1,
        name: "MySQL测试库",
        type: DataSourceType.MySQL,
        host: "localhost",
        port: 3306,
        database: "test_db",
        username: "root",
        password: "123456",
        status: DataSourceStatus.Connected,
        createdAt: "2023-06-01 10:00:00",
        updatedAt: "2023-06-01 10:00:00",
      },
      {
        id: 2,
        name: "PostgreSQL数据仓库",
        type: DataSourceType.PostgreSQL,
        host: "192.168.1.100",
        port: 5432,
        database: "data_warehouse",
        username: "postgres",
        password: "postgres",
        status: DataSourceStatus.Disconnected,
        createdAt: "2023-06-02 14:30:00",
        updatedAt: "2023-06-02 14:30:00",
      },
      {
        id: 3,
        name: "Oracle企业库",
        type: DataSourceType.Oracle,
        host: "oracle-server",
        port: 1521,
        database: "ORCL",
        username: "system",
        password: "manager",
        status: DataSourceStatus.Error,
        createdAt: "2023-06-03 09:15:00",
        updatedAt: "2023-06-03 09:15:00",
      },
    ];
  }
  return _mockDataSources;
};

// 获取数据源列表 - 使用函数来获取模拟数据
export const getDataSourceList = async (params: {
  keyword?: string;
  page?: number;
  pageSize?: number;
}) => {
  try {
    // 模拟网络延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 获取模拟数据
    let filtered = [...getMockDataSources()];

    // 如果有关键字，进行过滤
    if (params.keyword) {
      filtered = filtered.filter((item) =>
        item.name.toLowerCase().includes(params.keyword!.toLowerCase())
      );
    }

    // 分页
    const start = ((params.page || 1) - 1) * (params.pageSize || 10);
    const end = start + (params.pageSize || 10);
    const paged = filtered.slice(start, end);

    return {
      data: {
        code: 0,
        message: "成功",
        data: {
          list: paged,
          total: filtered.length,
        },
      },
    };
  } catch (error) {
    console.error("模拟数据源列表获取失败:", error);
    // 返回一个错误但格式正确的响应，避免解析错误
    return {
      data: {
        code: 500,
        message: "获取数据源列表失败",
        data: {
          list: [],
          total: 0,
        },
      },
    };
  }
};

// 创建数据源
export const createDataSource = async (
  data: Omit<DataSource, "id" | "status">
) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  const newDataSource = {
    ...data,
    id: getMockDataSources().length + 1,
    status: DataSourceStatus.Disconnected,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };

  getMockDataSources().push(newDataSource);

  return {
    data: {
      code: 0,
      message: "创建成功",
      data: newDataSource,
    },
  };
};

// 更新数据源
export const updateDataSource = async (
  id: number,
  data: Partial<DataSource>
) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  const index = getMockDataSources().findIndex((item) => item.id === id);

  if (index === -1) {
    return {
      data: {
        code: 404,
        message: "数据源不存在",
        data: null,
      },
    };
  }

  const updatedDataSource = {
    ...getMockDataSources()[index],
    ...data,
    updatedAt: new Date().toISOString(),
  };

  getMockDataSources()[index] = updatedDataSource;

  return {
    data: {
      code: 0,
      message: "更新成功",
      data: updatedDataSource,
    },
  };
};

// 删除数据源
export const deleteDataSource = async (id: number) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  const index = getMockDataSources().findIndex((item) => item.id === id);

  if (index === -1) {
    return {
      data: {
        code: 404,
        message: "数据源不存在",
        data: null,
      },
    };
  }

  const deletedDataSource = getMockDataSources()[index];
  getMockDataSources().splice(index, 1);

  return {
    data: {
      code: 0,
      message: "删除成功",
      data: deletedDataSource,
    },
  };
};

// 测试数据源连接
export const testDataSourceConnection = async (id: number) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 800));

  const dataSource = getMockDataSources().find((item) => item.id === id);

  if (!dataSource) {
    return {
      success: false,
      message: "数据源不存在",
    };
  }

  // 模拟连接成功率80%
  const success = Math.random() > 0.2;

  console.log("测试连接结果:", {
    success,
    message: success ? "连接成功" : "连接失败，请检查配置",
  });

  return {
    success,
    message: success ? "连接成功" : "连接失败，请检查配置",
  };
};

export const getTableList = async (
  dataSourceId: number
): Promise<TableListResponse> => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  return {
    tables: [
      { name: "users", comment: "用户表", type: "table" },
      { name: "orders", comment: "订单表", type: "table" },
      { name: "products", comment: "商品表", type: "table" },
    ],
    views: [
      { name: "order_details", comment: "订单详情视图", type: "view" },
      { name: "product_stats", comment: "商品统计视图", type: "view" },
    ],
  };
};

export const getTableStructure = async (
  dataSourceId: number,
  tableName: string
): Promise<ColumnInfo[]> => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  return [
    {
      name: "id",
      type: "int",
      nullable: false,
      key: "PRI",
      comment: "主键ID",
    },
    {
      name: "name",
      type: "varchar(50)",
      nullable: false,
      comment: "名称",
    },
    {
      name: "status",
      type: "tinyint",
      nullable: false,
      default: "1",
      comment: "状态",
    },
    {
      name: "created_at",
      type: "datetime",
      nullable: true,
      comment: "创建时间",
    },
  ];
};

export const getTableData = async (
  dataSourceId: number,
  tableName: string,
  query: TableDataQuery
): Promise<TableDataResponse> => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  const mockData = Array.from({ length: 100 }, (_, i) => ({
    id: i + 1,
    name: `${tableName} 数据 ${i + 1}`,
    status: Math.random() > 0.5 ? 1 : 0,
    created_at: new Date().toISOString(),
  }));

  const start = (query.page - 1) * query.pageSize;
  const end = start + query.pageSize;

  return {
    list: mockData.slice(start, end),
    total: mockData.length,
  };
};

// 获取数据源结构
export const getDataSourceStructure = async (dataSourceId: number) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  // 模拟数据库结构
  return {
    data: {
      code: 0,
      message: "成功",
      data: [
        {
          id: "tables",
          label: "表",
          type: "folder",
          children: [
            { id: "users", label: "users (用户表)", type: "table" },
            { id: "orders", label: "orders (订单表)", type: "table" },
            { id: "products", label: "products (商品表)", type: "table" },
          ],
        },
        {
          id: "views",
          label: "视图",
          type: "folder",
          children: [
            {
              id: "order_details",
              label: "order_details (订单详情视图)",
              type: "view",
            },
            {
              id: "product_stats",
              label: "product_stats (商品统计视图)",
              type: "view",
            },
          ],
        },
      ],
    },
  };
};

// SQL预览
export const previewSql = async (dataSourceId: number, sql: string) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 800));

  // 根据SQL语句模拟不同的结果
  let columns = ["id", "name", "status"];
  let data = [];

  if (
    sql.toLowerCase().includes("select") &&
    sql.toLowerCase().includes("from")
  ) {
    // 模拟查询数据
    data = Array.from({ length: 10 }, (_, i) => ({
      id: i + 1,
      name: `测试数据 ${i + 1}`,
      status: Math.random() > 0.5 ? 1 : 0,
    }));
  } else if (sql.toLowerCase().includes("insert")) {
    // 模拟插入结果
    columns = ["affected_rows"];
    data = [{ affected_rows: 1 }];
  } else if (sql.toLowerCase().includes("update")) {
    // 模拟更新结果
    columns = ["affected_rows"];
    data = [{ affected_rows: Math.floor(Math.random() * 5) + 1 }];
  } else if (sql.toLowerCase().includes("delete")) {
    // 模拟删除结果
    columns = ["affected_rows"];
    data = [{ affected_rows: Math.floor(Math.random() * 3) }];
  }

  return {
    data: {
      code: 0,
      message: "执行成功",
      data: {
        columns,
        data,
      },
    },
  };
};

// 使用配置测试连接（不保存数据源）
export const testConnectionWithConfig = async (config: {
  type: DataSourceType;
  host: string;
  port: number;
  database: string;
  username: string;
  password: string;
}) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 800));

  // 验证必填字段
  const requiredFields = ["host", "port", "database", "username", "password"];
  for (const field of requiredFields) {
    if (!config[field as keyof typeof config]) {
      return {
        success: false,
        message: `缺少必填字段: ${field}`,
      };
    }
  }

  // 模拟连接成功率80%
  const success = Math.random() > 0.2;

  console.log("使用配置测试连接结果:", {
    success,
    message: success ? "连接成功" : "连接失败，请检查配置",
  });

  return {
    success,
    message: success ? "连接成功" : "连接失败，请检查配置",
  };
};

// 根据数据源类型和 SQL 生成模拟数据
export function generateMockDataForSql(
  dataSourceType: string,
  sql: string
): any[] {
  console.log(`为数据源类型 ${dataSourceType} 生成 SQL 执行结果:`, sql);

  // 尝试解析简单的 SQL 来确定表名和列
  let targetTable = "";
  const sqlLower = sql.toLowerCase();

  // 简单的 SELECT 解析
  if (sqlLower.includes("select") && sqlLower.includes("from")) {
    const fromParts = sqlLower.split("from");
    if (fromParts.length > 1) {
      // 尝试提取表名
      const tablePart = fromParts[1].trim().split(/\s|;/)[0];
      targetTable = tablePart;
    }
  }

  console.log(`解析的目标表: ${targetTable}`);

  // 为不同数据库类型生成对应的模拟数据
  switch (dataSourceType) {
    case "mysql": {
      if (targetTable === "users") {
        return [
          {
            id: 1,
            username: "john_doe",
            email: "john@example.com",
            created_at: "2023-01-15 10:20:30",
          },
          {
            id: 2,
            username: "jane_smith",
            email: "jane@example.com",
            created_at: "2023-02-20 14:30:45",
          },
          {
            id: 3,
            username: "alex_wong",
            email: "alex@example.com",
            created_at: "2023-03-10 09:15:00",
          },
        ];
      } else if (targetTable === "orders") {
        return [
          {
            id: 101,
            user_id: 1,
            amount: 150.5,
            status: "completed",
            order_date: "2023-04-01 12:30:00",
          },
          {
            id: 102,
            user_id: 2,
            amount: 75.2,
            status: "processing",
            order_date: "2023-04-02 09:45:00",
          },
          {
            id: 103,
            user_id: 1,
            amount: 210.75,
            status: "completed",
            order_date: "2023-04-03 16:20:00",
          },
        ];
      }
      break;
    }
    case "postgresql": {
      if (targetTable === "accounts") {
        return [
          {
            id: 1,
            name: "Corporate Account",
            email: "corp@example.com",
            created_on: "2023-01-10",
          },
          {
            id: 2,
            name: "Personal Account",
            email: "personal@example.com",
            created_on: "2023-02-15",
          },
          {
            id: 3,
            name: "Business Account",
            email: "business@example.com",
            created_on: "2023-03-20",
          },
        ];
      } else if (targetTable === "transactions") {
        return [
          {
            id: 101,
            account_id: 1,
            amount: 500.0,
            transaction_date: "2023-04-01",
            type: "deposit",
          },
          {
            id: 102,
            account_id: 2,
            amount: -50.25,
            transaction_date: "2023-04-02",
            type: "withdrawal",
          },
          {
            id: 103,
            account_id: 1,
            amount: -200.0,
            transaction_date: "2023-04-03",
            type: "transfer",
          },
        ];
      }
      break;
    }
    case "sqlserver": {
      if (targetTable === "employees") {
        return [
          {
            EmployeeID: 1,
            FirstName: "John",
            LastName: "Doe",
            Department: "IT",
            HireDate: "2022-06-15",
          },
          {
            EmployeeID: 2,
            FirstName: "Jane",
            LastName: "Smith",
            Department: "HR",
            HireDate: "2021-09-20",
          },
          {
            EmployeeID: 3,
            FirstName: "Robert",
            LastName: "Johnson",
            Department: "Finance",
            HireDate: "2023-01-10",
          },
        ];
      } else if (targetTable === "customers") {
        return [
          {
            CustomerID: "ALFKI",
            CompanyName: "Alfreds Futterkiste",
            ContactName: "Maria Anders",
            Address: "Obere Str. 57",
            City: "Berlin",
            Country: "Germany",
          },
          {
            CustomerID: "ANATR",
            CompanyName: "Ana Trujillo",
            ContactName: "Ana Trujillo",
            Address: "Avda. de la Constitución 2222",
            City: "México D.F.",
            Country: "Mexico",
          },
          {
            CustomerID: "ANTON",
            CompanyName: "Antonio Moreno",
            ContactName: "Antonio Moreno",
            Address: "Mataderos 2312",
            City: "México D.F.",
            Country: "Mexico",
          },
        ];
      }
      break;
    }
    default: {
      // 默认数据
      return [
        { id: 1, name: "Item 1", value: "Value 1" },
        { id: 2, name: "Item 2", value: "Value 2" },
        { id: 3, name: "Item 3", value: "Value 3" },
      ];
    }
  }

  // 如果没有匹配到特定表，返回通用数据
  return [
    { id: 1, name: "Default Row 1", value: Math.round(Math.random() * 100) },
    { id: 2, name: "Default Row 2", value: Math.round(Math.random() * 100) },
    { id: 3, name: "Default Row 3", value: Math.round(Math.random() * 100) },
  ];
}
